<template>
  <div>
    <el-dialog title="" v-model="isDialogVisible" width="60%" :before-close="handleClose" draggable destroy-on-close>
      <!-- 为 title 添加样式 -->
      <div class="dialog-title">{{ title }}</div>
      <!-- 图表容器 -->
      <div ref="chartRef" style="width: 100%; height: 400px" />
      <!-- 对话框底部操作按钮 -->
      <template #footer>
        <el-button @click="closeDialog">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, defineExpose } from "vue"
import * as echarts from "echarts"
import "echarts/renderers"
import { companyMonthlyTradeDataApi } from "@/api/conventional"

// 对话框显示状态
const isDialogVisible = ref(false)

// 图表容器引用
const dateList = ref<any[]>([])
const chartRef = ref<any>(null)
const tableData = ref<any[]>([])
const title = ref<string>("")

const eaChartss = () => {
  if (chartRef.value) {
    const chartInstance = echarts.init(chartRef.value)
    const option = {
      tooltip: {},
      legend: {
        data: ["贴现", "买票"]
      },
      xAxis: [
        {
          type: "category",
          data: dateList.value
        }
      ],
      yAxis: [
        {
          name: "单位：万元",
          type: "value",
          scale: true, // 强制为连续坐标轴
          min: 0, // 最小值
          max: 200, // 最大值
          splitNumber: 10, // 刻度数量
          interval: 20, // 每个刻度的间隔
          axisLabel: {
            formatter: function (value: any) {
              return [10, 20, 30, 50, 100, 200, 300, 500].find((v) => v === value) || value
            }
          }
        }
      ],
      series: tableData.value
    }
    chartInstance.setOption(option, true)
  }
}
const searchData = reactive({
  id: 0,
  year: "",
  month: ""
})
const getTableData = async () => {
  try {
    const res = await companyMonthlyTradeDataApi({
      id: searchData.id,
      dateType: "month",
      year: searchData.year,
      month: searchData.month
    })
    tableData.value = res.data.data
    dateList.value = res.data.date
    eaChartss()
  } catch (error) {
    tableData.value = []
  } finally {
    // Intentionally left blank
    console.log("API 调用完成")
  }
}

// 打开对话框函数
const openDialog = (row: any) => {
  searchData.id = row.id
  searchData.year = row.year
  searchData.month = row.month
  title.value = row.company_name + " " + row.year + "年" + row.month + "月"
  getTableData()
  nextTick(() => {
    eaChartss()
  })
  isDialogVisible.value = true
}

// 关闭对话框函数
const closeDialog = () => {
  searchData.id = 0
  searchData.year = ""
  searchData.month = ""
  isDialogVisible.value = false
}
const handleClose = (done: () => void) => {
  closeDialog()
  done()
}
// 将函数暴露给外部
defineExpose({
  openDialog
})
</script>

<style scoped>
/* 添加自定义样式 */
.dialog-title {
  text-align: center; /* 水平居中 */
  padding: 10px 0; /* 上下距离 10px */
  font-weight: bold; /* 字体加粗（可选） */
  font-size: 24px; /* 字体大小为 24px */
  line-height: 1; /* 行高（让文字紧贴上下边距） */
}
</style>
